<template>
    <div class="show_report" id="show_report" ref="show_report">
      <div style="padding-bottom: 24px">
        <a-row type="flex" justify="start" align="middle">
          <a-col>
            <p class="report_title">{{title}}</p>
          </a-col>
          <a-col>
            <p class="follow_icon"><a-icon
              type="star"
              :theme="followIconTheme"
              v-on:click="changeFollowingStatus"
            ></a-icon></p>
          </a-col>
        </a-row>



      </div>
      <a-card :bordered="false" class="search_show_report" v-if="form_view.length">
        <div class="table-page-search-wrapper">
          <a-form layout="horizontal" :labelCol="{span:8}" :wrapperCol="{span: 16, offset: 0}">
            <a-row :gutter="{xs: 10, sm: 15, md: 20, lg: 25, xl: 30}" align="bottom">
              <a-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" v-for="(item, index) in form_view" :key="index">
                <a-form-item :label="item.name">
                  <template v-if="item.type == 'input'">
                    <a-input placeholder="请输入" v-model="form[item.name]"  />
                  </template>
                  <template v-if="item.type == 'select'">
                    <a-select
                      :maxTagTextLength="100"
                      show-search v-model="form[item.name]"
                      placeholder="请选择"
                      :loading="loading1"
                      @dropdownVisibleChange="onDropdownSelect(item, $event)"
                      @search="onSearchSelectValue1(item, $event)"
                      allow-clear
                    >
                      <a-select-option v-for="(sele1, index) in selectsArr1" :value="sele1.value" :key ="sele1.value +'-'+ index">
                        {{sele1.displayName}}
                      </a-select-option>
                    </a-select>
                  </template>
                  <template v-if="item.type == 'selects'">
                    <a-select
                      mode="multiple"
                      show-search
                      placeholder="请选择"
                      v-model="form[item.name]"
                      :loading="loading2"
                      @dropdownVisibleChange="onDropdownSelects(item, $event)"
                      @search="onSearchSelectValue2(item, $event)"
                      allow-clear
                    >
                      <a-select-option v-for="(sele2, idx) in selectsArr2" :value="sele2.value" :key ='sele2.value + "-" +idx'>
                        {{sele2.displayName}}
                      </a-select-option>
                    </a-select>
                  </template>
                  <template v-if="item.type == 'date-range'">
                    <a-range-picker v-model="form[item.name]" @change="onRangePicker(item.name, $event)" />
                  </template>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="12" :lg="8" :xl="8" style="float: right;">
                <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" @click="onSearch" :loading="search_loading">查询</a-button>
                  <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
                  <a @click="toggleAdvanced" style="margin-left: 8px">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'"/>
                  </a>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
      <grid-layout
          :layout.sync="layout"
          :col-num="24"
          :row-height="itemGridHeight"
          :is-draggable="false"
          :is-resizable="false"
          :is-mirrored="false"
          :vertical-compact="false"
          :margin="[10, 10]"
          :auto-size="false"
          :static="true"
          :use-css-transforms="true"
          ref="grid_layout"
        >
            <grid-item
              v-for="item in layout"
              :x="item.x"
              :y="item.y"
              :w="item.w"
              :h="item.h"
              :i="item.i"
              :key="item.i"
              style="touch-action: none;"
            >
                <a-card style="width: 100%; height: 100%;padding: 8px 4px 2px 4px;">
                    <div class="card-title">
                        <div class="card-title_title">
                            <div class="chart_title">
                              {{getChartInfo(item.i).title}}
                            </div>
                            <div class="chart_action" v-if="getChartInfo(item.i).type == 'table'">
                              <a-button type="link" size="small" @click="onExportExcel(getChartInfo(item.i))">导出excel</a-button>
                            </div>
                        </div>
                        <div class="card-title_remark" v-show="getChartInfo(item.i).remark">
                            {{getChartInfo(item.i).remark}}
                        </div>
                    </div>
                    <!-- <ChartItem
                      :item="getChartInfo(item.i)"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                    /> -->
                    <NumberChart
                      v-if="getChartInfo(item.i).type == 'number'"
                      :item="getChartInfo(item.i)"
                      :remark="getChartInfo(item.i).remark"
                      :display="getChartInfo(item.i).display"
                      :dataMapping="getChartInfo(item.i).dataMapping"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                      :position="getChartInfo(item.i).position"
                      :ref="'chart_ref'+item.i"
                    >
                    </NumberChart>
                    <PathView
                      v-else-if="getChartInfo(item.i).type == 'path'"
                      :item="getChartInfo(item.i)"
                      :remark="getChartInfo(item.i).remark"
                      :display="getChartInfo(item.i).display"
                      :dataMapping="getChartInfo(item.i).dataMapping"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                      :position="getChartInfo(item.i).position"
                      :ref="'chart_ref'+item.i"
                    >
                    </PathView>
                    <Retention
                      v-else-if="getChartInfo(item.i).type == 'retention'"
                      :item="getChartInfo(item.i)"
                      :remark="getChartInfo(item.i).remark"
                      :display="getChartInfo(item.i).display"
                      :dataMapping="getChartInfo(item.i).dataMapping"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                      :position="getChartInfo(item.i).position"
                      :ref="'chart_ref'+item.i"
                    >
                    </Retention>
                    <TableChart
                      v-else-if="getChartInfo(item.i).type == 'table'"
                      :item="getChartInfo(item.i)"
                      :remark="getChartInfo(item.i).remark"
                      :display="getChartInfo(item.i).display"
                      :dataMapping="getChartInfo(item.i).dataMapping"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                      :position="getChartInfo(item.i).position"
                      :ref="'chart_ref'+item.i"
                    >
                    </TableChart>
                    <EchartItem
                      v-else
                      :item="getChartInfo(item.i)"
                      :remark="getChartInfo(item.i).remark"
                      :display="getChartInfo(item.i).display"
                      :dataMapping="getChartInfo(item.i).dataMapping"
                      :datasetList="datasetList"
                      :itemGridHeight="itemGridHeight"
                      :search_loading="echarts_loading"
                      :position="getChartInfo(item.i).position"
                      :ref="'chart_ref'+item.i"
                    >
                    </EchartItem>
                </a-card>
            </grid-item>
        </grid-layout>
    </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex';
  import VueGridLayout from 'vue-grid-layout';
  import { export2Excel } from '@/excel/excel.config';
  import bus from '@/views/components/bus';
  import elementResize from '@/views/reportForms/show_report/elementResize';
  import { baseMixin } from '@/store/app-mixin';
  import EchartItem from './show_report/echarts_item.vue';
  import NumberChart from './show_report/number_chart.vue';
  import PathView from './show_report/pathView.vue';
  import Retention from './show_report/retention.vue';
  import TableChart from './show_report/table_chart.vue';
  import {debounce} from "@/components/OptimizeUtils";
  export default {
    mixins: [baseMixin],
    data () {
      return {
        followIconTheme: 'outlined',
        followingStatus: false,
        reportDetail: null,
        advanced: false,
        rowLength: 6,
        title: '报表展示',
        form: {},
        selectsArr1: [],
        selectsArr2: [],
        datasetList: {},
        chart_view: [],
        control_type: [],
        filter_open: [],
        loading1: false,
        loading2: false,
        itemGridHeight: 30,
        init_filters: [],
        init_datasetIds: [],
        search_loading: false,
        echarts_loading: false,
        filterSelectId: '',
        filterSelectValue: ''
      }
    },
    components: {
      GridLayout: VueGridLayout.GridLayout,
      GridItem: VueGridLayout.GridItem,
      EchartItem,
      NumberChart,
      PathView,
      Retention,
      TableChart
    },
    watch: {
      look_id () {
        this.selectsArr1 = [];
        this.selectsArr2 = [];
        this.filter_open = [];
        this.control_type = [];
        this.search_loading = true;
        this.init_report()
        this.$nextTick(()=> {
          this.setRowHeight()
        })
      },
      followingStatus (val){
        if (val){
          this.followIconTheme = 'filled'
        }else {
          this.followIconTheme = 'outlined'
        }
      }
    },
    computed: {
      ...mapState('reportManage', ['datail', 'dataset']),
      ...mapState('custom', ['report']),
      form_view () {
        if (this.advanced) {
          return this.filter_open
        } else {
          return this.control_type
        }
      },
      look_id () {
        if (this.$route.name == 'ShowReports' && this.$route.meta.title == '报表展示') {
          return this.$route.params.id;
        } else {
          return this.$route.meta.id;
        }
      },
      layout () {
        return this.chart_view.map(chart =>{
          return {...chart.position, 'i': `${chart.id}`};
        })
      }
    },
    methods: {
      ...mapActions('reportManage', [
        'getUpdateReportList',
        'query_report_detail',
        'query_dadaset_data',
        'query_filter_value',
        'getFollowingStatus',
        'followReport',
        'unfollowReport'
      ]),
      /**
       * 表格导出excel表
       */
      onExportExcel (value) {
        this.$confirm({
          title: '提示',
          content: `你确定要导出 ${value.title} 该表格里的数据吗`,
          onOk:()=> {
            let ref = this.$refs;
            let getVal = [];
            for (let key in ref) {
              if (key.includes('chart_ref')) {
                getVal.push(key);
              }
            }
            let data = null,
                columns = null;
            getVal.forEach(item => {
              if (this.$refs[item][0] && this.$refs[item][0].item.id == value.id) {
                columns = this.$refs[item][0].columns;
                data = this.$refs[item][0].datasetArr;
              }
            })
            export2Excel(columns, data, value.title);
          },
          onCancel() {},
        });
      },
      getChartInfo (id) {
        let chartVal = null;
        this.chart_view.forEach(chart=>{
          if (chart.id == id) {
            chartVal = chart;
          }
        })
        return chartVal;
      },
      onRangePicker (value, date) {
        if (date.length) {
          this.form[value] = [this.moment(date[0]).format('YYYY-MM-DD'), this.moment(date[1]).format('YYYY-MM-DD') ]
        }
      },
      // 展开收起
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      onSearchSelectValue1 (item, value) {
        this.filterSelectId = item.id;
        this.filterSelectValue = value;
        if (value) {
          this.loading1 = true;
          let query = debounce(this.getFilterValue1,1000);
          query(value);
        }
      },
      getFilterValue1 () {
        this.query_filter_value({ id: this.filterSelectId, reportId: this.look_id, query: {keyword: this.filterSelectValue} })
          .then(res => {
            this.loading1 = false;
            this.selectsArr1 = [...res.data];
          })
          .catch(error => {
            console.error(error)
            this.loading1 = false;
          })
      },
      getFilterValue2 () {
        this.query_filter_value({ id: this.filterSelectId, reportId: this.look_id, query: {keyword: this.filterSelectValue} })
          .then(res => {
            this.loading2 = false;
            this.selectsArr2 = [...res.data];
          })
          .catch(error => {
            console.error(error)
            this.loading2 = false;
          })
      },
      onSearchSelectValue2 (item, value) {
        this.filterSelectId = item.id;
        this.filterSelectValue = value;
        if (value) {
          this.loading2 = true;
          let query = debounce(this.getFilterValue2,1000);
          query(value)
        }
      },
      onDropdownSelect (item, e) {
        if (e) {
          this.query_filter_value({ id: item.id, reportId: this.look_id })
            .then(res=> {
              this.selectsArr1 = [...res.data];
            })
            .catch(error => {
              console.error(error)
              this.loading1 = false;
            })
        }
      },
      onDropdownSelects (item, e) {
        if (e) {
          this.query_filter_value({ id: item.id, reportId: this.look_id })
            .then(res=> {
              this.selectsArr2 = [...res.data];
            })
            .catch(error => {
              console.error(error)
              this.loading2 = false;
            })
        }
      },
      onReset (){
        this.form = {}
        this._set_filter(this.reportDetail)
      },
      onSearch () {
        this.search_loading = true;
        this.echarts_loading = true;
        let queryForm = this.queryFilterForm(this.form, this.init_filters, this.init_datasetIds);
        let deleteArr = [],
          retainArr = [];
        for (let key in queryForm) {
          if (queryForm[key].length == 0) {
            deleteArr.push(key);
          } else {
            retainArr.push(key)
          }
        }
        retainArr.forEach(data => {
          delete this.datasetList[data]
        })
        let wait = []
        retainArr.forEach(data => {
          wait.push(this.PromiseData({id: data, filter: JSON.stringify(queryForm[data])}))
        })
        let promiseArr = wait.filter(item => {
          if(item) {return item}
        })
        Promise.all(promiseArr.map(item=>item.catch((error)=>{
          console.error(error)
          status: 'failed'
        }))).then(res =>{
          this.$nextTick(() => {
            this.layout.forEach(chart => {
              let type = this.$refs['chart_ref' + chart.i][0].item.type;
              let vNode = this.$refs['chart_ref' + chart.i][0];
              if (type == 'table') {
                vNode.dataConfig();
                vNode.initTableConfig();
              } else if (type == 'number') {
                vNode.initNumber();
              } else if (type == 'path') {
                vNode.reset_sankeyHeight();
              } else if (type == 'retention') {
                vNode.tableInit();
              } else {
                vNode.initCharts();
              }
            })
          })
          this.search_loading = false;
          this.echarts_loading = false;
        }).catch(error => {
          console.error(error)
          this.search_loading = false;
          this.echarts_loading = false;
        })
      },
      _set_filter (detail) {
        if (!this.reportDetail) return;
        this.init_filters = detail.data.filters.map( filter => {
          // 根据筛选信息的控件类型对数据做处理
          if (filter.type == 'date-range') {
            let filterDefaultValue = JSON.parse(filter.defaultValue);
            if (filterDefaultValue.type == 'absolute') {
              let date_Array = (filterDefaultValue.values);
              this.$set(this.form, filter.name, [this.moment(date_Array[0]).format('YYYY-MM-DD'), this.moment(date_Array[1]).format('YYYY-MM-DD') ])
            } else {
              let date_Array = (filterDefaultValue.values).split(',');
              this.$set(this.form, filter.name, [this.moment().subtract(parseInt(date_Array[0]), 'days').format('YYYY-MM-DD'), this.moment().subtract(parseInt(date_Array[1]), 'days').format('YYYY-MM-DD') ])
            }
          } else {
            // 当控件类型为多选下拉菜单，需要将默认值转为数组
            if (filter.type == 'selects') {
              let filterDefaultValue = filter.defaultValue;
              this.$set(this.form, filter.name, filterDefaultValue ? filterDefaultValue.split(',') : [])
            } else {
              this.$set(this.form, filter.name, filter.defaultValue)
            }
          }
          let filterVal = null;
          if (filter.type == 'date-range') {
            filterVal = {...filter, config: JSON.parse(filter.config), defaultValue: JSON.parse(filter.defaultValue)}
          } else {
            filterVal = {...filter, config: JSON.parse(filter.config), defaultValue: filter.defaultValue}
          }
          return filterVal;
        })
      },
      init_report () {
        // 获取当前查看报表的基本信息
        this.echarts_loading = true;
        this.look_id && this.getUpdateReportList({id: this.look_id})
          .then(report =>{
            this.title = report.data.name
          })
          .catch(err => {
            console.error(err)
            if (err.code == 401) {
              this.err401(err)
              return
            }
            this.$message.error('获取报表失败，原因：' + err.msg + '！')
          })
        // 获取当前查看报表的详情（图表配置、筛选字段配置）
        this.look_id && this.query_report_detail({id: this.look_id})
          .then(detail => {
            this.reportDetail = JSON.parse(JSON.stringify(detail))
            // 当前报表使用的数据集
            this.init_datasetIds =  detail.data.datasetIds
            // 当前报表配置的图表信息
            this.chart_view = detail.data.charts.map( item => {
              return {...item, dataMapping: JSON.parse(item.dataMapping), display: JSON.parse(item.display), position: JSON.parse(item.position)}
            })
            // 当前报表的筛选信息
            this._set_filter(detail)
            // 设置控件排列
            this.init_filters.forEach((filter, index) => {
              if (index < 2) {
                this.control_type.push({type: filter.type, name: filter.name, id: filter.id})
              }
              this.filter_open.push({type: filter.type, name: filter.name, id: filter.id})
            })

            let queryForm = this.queryFilterForm(this.form, this.init_filters, this.init_datasetIds)
            this.datasetList = {}
            let wait = [];
            this.init_datasetIds.forEach(data => {
              wait.push(this.PromiseData({id: data, filter: JSON.stringify(queryForm[data])}))
            })

            let promiseAll = wait.filter(item => {
              if (item) return item
            })

            Promise.all(promiseAll.map(item=>item.catch((e)=>{
              console.error(e)
              status: 'failed'
            })))
              .then(res => {
                this.$nextTick(() => {
                  this.layout.forEach(chart => {
                    let type = this.$refs['chart_ref' + chart.i][0].item.type;
                    let vNode = this.$refs['chart_ref' + chart.i][0];
                    if (type == 'table') {
                      vNode.dataConfig();
                      vNode.initTableConfig();
                    } else if (type == 'number') {
                      vNode.initNumber();
                    } else if (type == 'path') {
                      vNode.reset_sankeyHeight();
                    } else if (type == 'retention') {
                      vNode.tableInit();
                    } else {
                      vNode.initCharts();
                    }
                  })
                  this.echarts_loading = false;
                  this.search_loading = false;
                })
              })
              .catch(err => {
                console.error(err)
                this.echarts_loading = false;
                this.search_loading = false;
              })

            let reportHeight = this.layout.sort((a, b)=> {
              return a.y-b.y
            })
            if (reportHeight.length == 0) {
              return
            }
            this.$refs.show_report.style.height = `${(reportHeight[reportHeight.length-1].y + reportHeight[reportHeight.length-1].h) * (this.itemGridHeight+20)}px`;
          })
        this.getFollowingStatusData()
      },
      // 配置查询参数
      queryFilterForm (Query, filters, datasetIds) {
        // 以{key:value}的形式生成每个数据集的查询参数
        let filterValue = {}
        for (let j = 0; j < datasetIds.length; j++) {
          // 生成每个数据集对应的数组存放条件
          filterValue[datasetIds[j]] = []
          for (let i = 0; i < filters.length; i++) {
            // 控件类型为日期时，需要做start和end的特殊处理
            if (filters[i].type == 'date-range') {
              let config_start = filters[i].config.start,
                  config_end = filters[i].config.end,
                  count = 0;
              for (let m = 0; m < config_start.length; m++) {
                if (config_start[m].datasetId == datasetIds[j]) {
                  for (let key in Query) {
                    if (filters[i].name == key) {
                      filterValue[datasetIds[j]].push({
                        filterName: config_start[m].filterName,
                        value: Query[key][count]
                      })
                      count = 1;
                    }
                  }
                }
              }
              for (let n = 0; n < config_end.length; n++) {
                if (config_end[n].datasetId == datasetIds[j]) {
                  for (let key in Query) {
                    if (filters[i].name == key) {
                      filterValue[datasetIds[j]].push({
                        filterName: config_end[n].filterName,
                        value: Query[key][count]
                      })
                      count = 1;
                    }
                  }
                }
              }
            } else {
              let config_item = filters[i].config
              for (let o = 0; o <config_item.length; o++) {
                if (config_item[o].datasetId == datasetIds[j]) {
                  for(let key in Query) {
                    if (filters[i].name == key) {
                      // 当控件类型为单选和多选 需要转换数据类型
                      if (filters[i].type == 'select' || filters[i].type == 'selects') {
                        if (Query[key]) {
                          filterValue[datasetIds[j]].push({
                            filterName: config_item[o].filterName,
                            value: Query[key] instanceof Array ? Query[key] : Query[key].split(',')
                          })
                        } else {
                          filterValue[datasetIds[j]].push({
                            filterName: config_item[o].filterName,
                            value: Query[key]
                          })
                        }
                      } else {
                        filterValue[datasetIds[j]].push({
                          filterName: config_item[o].filterName,
                          value: Query[key]
                        })
                      }
                    }
                  }
                }
              }
            }
          }
        }
        return filterValue
      },
      PromiseData (params) {
        return new Promise((resolve, reject) => {
          this.query_dadaset_data(params)
            .then(res=>{
              this.$set(this.datasetList, params.id, res.data)
              resolve(res.data)
            })
            .catch(err => {
              reject(err)
              this.$message.error('查询错误，原因：' + err.msg + '！')
              setTimeout(() => {
                this.search_loading = false;
              }, 1500)
              console.error(err)
            })
        })
      },
      setRowHeight () {
        let rowH = this.$refs.show_report && this.$refs.show_report.offsetWidth
        this.itemGridHeight = Math.floor(rowH/24)-15;
      },
      getFollowingStatusData(){
        this.getFollowingStatus(this.look_id).then(res => {
          this.followingStatus = !!(res && res.id)
        }).catch(err => {
          this.$message.success('获取关注状态失败: ' + err.msg)
        })
      },
      changeFollowingStatus(){
        if (this.followingStatus){
          this.unfollowReport(this.look_id).then(() =>{
            this.followingStatus = !this.followingStatus
            this.$message.success('取消关注成功')
          }).catch(err => {
            this.$message.success('取消关注失败: ' + err.msg)
          })
        }else {
          this.followReport(this.look_id).then(() =>{
            this.followingStatus = !this.followingStatus
            this.$message.success('关注报表成功')
          }).catch(err => {
            this.$message.success('关注报表失败: ' + err.msg)
          })
        }

      }
    },
    created () {
      this.init_report()
    },
    mounted() {
        this.setRowHeight()
        elementResize.on(document.getElementById('show_report'), () => {
            let rowH = this.$refs.show_report && this.$refs.show_report.offsetWidth
            this.itemGridHeight = Math.floor(rowH/24)-15;
        })
    },
  }
</script>

<style scoped>
.report_title {
  font-size: 24px;
  font-weight: bold;
  margin: auto;
}

.follow_icon {
  font-size: 20px;
  padding-left: 5px;
  margin: auto;
  color: #ee8b49;
}


.search_show_report {
  width: 100%;
  padding: 24px 24px 0px;
  /* margin-bottom: 12px; */
}

.show_report {
  width: 100%;
  height: 100%;
}

.show_report>>>.ant-card-body{
  width: 100%;
  height: 100%;
  padding: 0px;
}

.card-title_title {
  display: flex;
  justify-content: space-between;
}

.chart_title {
  font-size: 14px;
  color: #555;
  text-indent: 10px;
  line-height: 30px;
}

.card-title_remark {
  padding-right: 20px;
  font-size: 12px;
  line-height: 20px;
  color: #8492a6;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-indent: 10px;
  margin-bottom: 2px;
}

.chart_action {
  display: flex;
  align-items: center;
}

.show_report >>> span.table-page-search-submitButtons {
  float: right;
}

.show_report >>> .vue-grid-layout {
  width: calc(100% + 20px);
  margin-left: -10px;
}

.search_show_report .search_show_report >>>label {
  overflow: hidden;
}

.show_report {
  flex: 1;
}


</style>

<style>
  .ant-layout-content,
  .ant-pro-basicLayout-children-content-wrap {
    height: 100% !important;
  }

  .ant-pro-grid-content {
    display: flex !important;
  }
</style>
